package com.wavefax.minbang.xu.learning.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CsvToJsonUtil {
    public void readcsv(String path){
        String pathTwo = "D:/wavefax/jsons";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//获取时间戳
        String timeStamp = sdf.format(new Date());
        try{
            BufferedReader bf = new BufferedReader(new FileReader(path));
            BufferedWriter writer = new BufferedWriter(new FileWriter(pathTwo+"/"+timeStamp+".json"));
            String head = "";
            head = bf.readLine();
            String[] heads = head.split(",");//取得csv文件头
            int columnNum = 0;
            columnNum = heads.length;
            String row = "";
            String[] rows;
            while((row = bf.readLine())!=null ){//一行一行地读
                rows = row.split(",");
                JSONObject jsonObject = new JSONObject();
                for(int i=0;i<columnNum;i++){
                    jsonObject.put(heads[i],rows[i]);
                }
                writer.append(jsonObject.toJSONString()+"\n");
                writer.flush();
            }
            writer.close();
            System.out.println("读取csv文件内容写到json文件成功，路径为:"+pathTwo+"/"+timeStamp+".json");
        }catch (Exception e){

        }
    }
}
